home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part1 / 1549 < prev    next >
Encoding:
Text File  |  1996-08-06  |  1.7 KB  |  72 lines

  1. Path: news.rain.org!usenet
  2. From: "Guus Leeuw jr." <guusl@eiffel.com>
  3. Newsgroups: comp.lang.c++
  4. Subject: Re: Deep/Shallow Copying?
  5. Date: Thu, 11 Jan 1996 08:25:05 -0800
  6. Organization: ISE Inc. http://www.eiffel.com
  7. Message-ID: <30F539E1.661A57DB@eiffel.com>
  8. References: <4d1bhe$1lto@bocanews.bocaraton.ibm.com>
  9. NNTP-Posting-Host: @outback.eiffel.com
  10. Mime-Version: 1.0
  11. Content-Type: text/plain; charset=us-ascii
  12. Content-Transfer-Encoding: 7bit
  13. X-Mailer: Mozilla 2.0b3 (X11; I; Linux 1.2.8 i586)
  14.  
  15. pani@genius.tisl.soft.net wrote:
  16. > Hi Guys,
  17. >       What is Deep copying or Shallow copying? Is this something
  18. > to do with a Copy constructor?
  19. > Thanks for any help.
  20. > Pani.
  21.  
  22.   A deep copy is a copy where not only the current object (`this') is
  23. copied but also all, I repeat all, objects that `this' references.
  24.  
  25.   A shallow copy is a copy where the current object (`this') is copied
  26. but the pointers to other objects are kept as they are (i.e. referenced
  27. objects will not be copied).
  28.  
  29.   You can simulate both kinds of behavior in your copy constructor.
  30.  
  31.   For a deep copy, you will need copy constructors for the classes of
  32. the referenced objects aswell. That will result in a chain of calls to
  33. copy constructors.
  34.  
  35.   For example:
  36.     class A
  37.     {
  38.         public:
  39.             A();    // std ctor
  40.             A(A&);    // copy ctor
  41.  
  42.             B *b;
  43.             C *c;
  44.     }
  45.  
  46.     A::A(A& other)
  47.     {
  48.         b = new B(*(other.b));
  49.         c = new C(*(other.c));
  50.     }
  51.  
  52.   Remark that the copy process will go down the whole branch of objects
  53. (i.e. if B has a pointer to an object of class D, that object has to be
  54. copied as well).
  55.  
  56.   For a shallow copy, however, you just assign the pointer values form
  57. `this' to the new object of the same type as `this'.
  58.  
  59.   For example:
  60.     same class A;
  61.  
  62.     A::A(A&)
  63.     {
  64.         b = other.b;
  65.         c = other.c;
  66.     }
  67.  
  68.  
  69. Hope this explains,
  70.     Guus Leeuw jr.
  71.